package mypetstore.web.servlet;

import mypetstore.domain.Product;
import mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductFormServlet extends HttpServlet {
    private CatalogService catalogService;
    private static final String SEARCH_PRODUCT_FORM = "/WEB-INF/jsp/catalog/searchProducts.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String keyword = req.getParameter("keyword");
        System.out.println("=== SearchProductFormServlet: 搜索关键词 = " + keyword + " ===");

        if (keyword == null || keyword.trim().isEmpty()) {  // 修正：isEmpty() 需要括号
            resp.sendRedirect("mainForm");
            return;
        }

        catalogService = new CatalogService();
        List<Product> productList = catalogService.searchProductList(keyword);  // 修正：使用 keyword 而不是 searchKeyword

        System.out.println("=== SearchProductFormServlet: 找到 " + productList.size() + " 个相关商品 ===");  // 修正：productList 变量名

        HttpSession session = req.getSession();
        session.setAttribute("searchKeyword", keyword);
        session.setAttribute("productList", productList);

        req.getRequestDispatcher(SEARCH_PRODUCT_FORM).forward(req, resp);
    }
}